package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.aspectj.weaver.ast.Or;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class OrderServiceImpl implements OrderService {

    private static final Logger log = LoggerFactory.getLogger(OrderServiceImpl.class);
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    WeChatPayUtil weChatPayUtil;
    @Autowired
    WebSocketServer webSocketServer;





    /***
     * 订单提交
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //判断是否会有异常
        AddressBook add = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (add == null) {//地址为空
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectAll(BaseContext.getCurrentId());
        if (shoppingCarts.isEmpty()) {//购物车为空
            throw new AddressBookBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //向订单表插入1条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setConsignee(add.getConsignee());
        orders.setUserId(BaseContext.getCurrentId());
        orders.setAddress(add.getDetail());
        orderMapper.insert(orders);

        Long ordersId = orders.getId();
        //向订单表插入n条数据
        List<OrderDetail>  orderDetailList=new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setOrderId(ordersId);
            orderDetailList.add(orderDetail);
        }
        //批量插入
        orderDetailMapper.insertBatch(orderDetailList);

        //清空购物车
        shoppingCartMapper.deleteAll(BaseContext.getCurrentId());


        //获取返回结果
        OrderSubmitVO orderSubmitVO =OrderSubmitVO.builder()
                .id(ordersId)
                .orderAmount(ordersSubmitDTO.getAmount())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .build();


        return orderSubmitVO;
    }


    /**
     * 请求微信支付api接口---调用微信下单接口
     * @param ordersPaymentDTO
     * @return
     * @throws Exception
     */
    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);
        //调用微信支付接口，生成预支付交易单
   /*     JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );*/
        JSONObject jsonObject = new JSONObject();
        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
        return vo;

    }

    /**
     * 支付成功修改订单信息
     * @param outTradeNo
     */
    @Override
    public void paySuccess(String outTradeNo) {
        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);
        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);

        //提醒商家端来单  采用websocket技术
        log.info("服务端通过socket发送来单提醒");
        Map map=new HashMap();
        map.put("type",1);
        map.put("orderId",orders.getId());
        map.put("content","订单号"+outTradeNo);
        String jsonString = JSONObject.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);




    }

    /**
     * 订单历史记录查询
     * @param page
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResult getHistoryOrders(Integer page, Integer pageSize, Integer status) {

        PageHelper.startPage(page,pageSize);
        Long userId = BaseContext.getCurrentId();
        List<Orders> ordersList=orderMapper.selectPage(status,userId);
        Page<OrderVO> p=new Page<>();
        p.setTotal(ordersList.size());

        for (Orders orders : ordersList) {
            Long ordersId = orders.getId();
            List<OrderDetail> orderDetailList=orderDetailMapper.getByOrderId(ordersId);
            OrderVO orderVO=new OrderVO();
            BeanUtils.copyProperties(orders,orderVO);
            orderVO.setOrderDetailList(orderDetailList);
            p.add(orderVO);
        }

        return new PageResult(p.getTotal(),p.getResult());

    }

    /**
     * 查看订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO getOrderDetail(Long id) {
        OrderVO orderVO=new OrderVO();
        Orders orders=orderMapper.getById(id);

        BeanUtils.copyProperties(orders,orderVO);

        List<OrderDetail> byOrderId = orderDetailMapper.getByOrderId(id);

        orderVO.setOrderDetailList(byOrderId);
        return orderVO;

    }

    /**
     * 取消订单
     * @param id
     * @throws Exception
     */
    @Override
    public void cancelOrder(Long id) throws Exception {
        //先判断是否能够取消
        Orders cancelOrder = orderMapper.getById(id);
        Integer status = cancelOrder.getStatus();
        if (cancelOrder==null){//没有该订单
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if (status!=Orders.PENDING_PAYMENT&&status!=Orders.TO_BE_CONFIRMED) {//此时不能取消订单，需要电联商家
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //如果订单是状态2  那就要取消付款
        if (status.equals(Orders.TO_BE_CONFIRMED)){
            //调用微信支付退款接口
 /*           weChatPayUtil.refund(
                    cancelOrder.getNumber(), //商户订单号
                    cancelOrder.getNumber(), //商户退款单号
                    new BigDecimal(0.01),//退款金额，单位 元
                    new BigDecimal(0.01));//原订单金额*/
            log.info("订单退款成功！");

            //支付状态修改为 退款
            cancelOrder.setPayStatus(Orders.REFUND);
        }

        //先把订单表中的状态设置为已取消
        cancelOrder.setStatus(Orders.CANCELLED);
        cancelOrder.setCancelTime(LocalDateTime.now());
        cancelOrder.setCancelReason("用户取消");
        orderMapper.update(cancelOrder);

    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    public void repetitionOrder(Long id) {

        Orders orders = orderMapper.getById(id);
        Long userId = BaseContext.getCurrentId();
        //该订单的详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        List<ShoppingCart> shoppingCarts = new ArrayList<>();

        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setUserId(userId);
            shoppingCarts.add(shoppingCart);
        }
        shoppingCartMapper.insertBatch(shoppingCarts);

    }

    /**
     * 用户端订单展示
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult getConditionSearchPage(OrdersPageQueryDTO ordersPageQueryDTO) {

        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<Orders> p=orderMapper.selectPageAdmin(ordersPageQueryDTO);
        return new PageResult(p.getTotal(),p.getResult());


    }


    /**
     * 展示订单详细信息
     * @param id
     * @return
     */
    @Override
    public OrderVO getDetailsAdmin(Long id) {
        Orders orders = orderMapper.getById(id);
        OrderVO orderVO=new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    /**
     * 统计各个状态的订单数量
     * @return
     */
    @Override
    public OrderStatisticsVO getStatistics() {
        OrderStatisticsVO orderStatisticsVO=new OrderStatisticsVO();
        Integer toBeConfirmed=orderMapper.getNumbertoBeConfirmed(Orders.TO_BE_CONFIRMED);
        Integer confirmed=orderMapper.getNumberconfirmed(Orders.CONFIRMED);
        Integer deliveryInProgress=orderMapper.getNumberdeliveryInProgress(Orders.DELIVERY_IN_PROGRESS);;
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    /**
     * 接单
     * @param id
     */
    @Override
    public void confirmOrder(Long id) {
        orderMapper.confirmOrder(id);
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejectionOrder(OrdersRejectionDTO ordersRejectionDTO) {
        //先判断订单是否是待接单状态
         Orders orders = orderMapper.selectById(ordersRejectionDTO.getId());
         if (orders.getStatus()!=Orders.TO_BE_CONFIRMED){//此时就不是待接单状态

             throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
         }
        //把订单改为已取消
        orderMapper.rejectionOrder(ordersRejectionDTO);
         //完成退款
        //调用微信支付退款接口
 /*           weChatPayUtil.refund(
                    cancelOrder.getNumber(), //商户订单号
                    cancelOrder.getNumber(), //商户退款单号
                    new BigDecimal(0.01),//退款金额，单位 元
                    new BigDecimal(0.01));//原订单金额*/
        log.info("订单退款成功！");
        orders.setPayStatus(Orders.REFUND);
        orders.setId(ordersRejectionDTO.getId());

        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 用户取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void cancelOrderAdmin(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = orderMapper.selectById(ordersCancelDTO.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        if (orders.getPayStatus()==Orders.PAID){//如果已支付，则退款
            //调用微信支付退款接口
 /*           weChatPayUtil.refund(
                    cancelOrder.getNumber(), //商户订单号
                    cancelOrder.getNumber(), //商户退款单号
                    new BigDecimal(0.01),//退款金额，单位 元
                    new BigDecimal(0.01));//原订单金额*/
            log.info("订单退款成功！");
            orders.setPayStatus(Orders.REFUND);
        }
        orderMapper.update(orders);
    }

    /**
     * 商家接单
     * @param id
     */
    @Override
    public void deliveryOrder(Long id) {
        Orders orders = orderMapper.getById(id);
        //只有状态为“待派送”的订单可以执行派送订单操作
        if(orders==null||orders.getStatus()!=Orders.CONFIRMED){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 更新订单状态,状态转为派送中
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders);
    }

    @Override
    public void complete(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);

        // 校验订单是否存在，并且状态为4
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        // 更新订单状态,状态转为完成
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());

        orderMapper.update(orders);
    }


    /**
     * 用户催单
     * @param id
     */
    @Override
    public void reminderOrder(Long id) {
        Orders orders = orderMapper.selectById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //提醒商家端来单  采用websocket技术
        log.info("服务端通过socket发送催单提醒");
        Map map=new HashMap();
        map.put("type",2);
        map.put("orderId",orders.getId());
        map.put("content","订单号"+orders.getNumber());
        String jsonString = JSONObject.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);
    }

}
